<script setup>
import MessageOverride from './components/MessageOverride.vue';
import { onMounted, ref, watch, provide } from 'vue';
import { useItemsStore } from './stores/items';
import { useSettingsStore } from './stores/settings';
import { useUserStore } from './stores/user';
import { usePermissionStore } from './stores/permission';
import { ElMessage } from 'element-plus';
import i18n from './i18n';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import enUs from 'element-plus/dist/locale/en.mjs';
import { messageHelper } from './utils/messageHelper';
import { messagesApi } from './utils/apiService';

const itemsStore = useItemsStore();
const settingsStore = useSettingsStore();
const userStore = useUserStore();
const permissionStore = usePermissionStore();
const isLoading = ref(true);
const elementLocale = ref(settingsStore.language === 'en-US' ? enUs : zhCn);
const loginTimesInitialized = ref(false);

// Provide login times initialization state to child components
provide('loginTimesInitialized', loginTimesInitialized);

// Watch for language changes
watch(() => settingsStore.language, (newLanguage) => {
  console.log('Language changed to:', newLanguage);
  // Update i18n locale
  i18n.global.locale.value = newLanguage;
  
  // Update Element Plus locale
  elementLocale.value = newLanguage === 'en-US' ? enUs : zhCn;
  
  // Update HTML lang attribute
  document.documentElement.setAttribute('lang', newLanguage.split('-')[0]);
}, { immediate: true });

// 在应用启动前立即初始化登录时间数据
(async function initAppData() {
  try {
    console.log('App.vue: 应用启动前初始化基础数据');
    
    // 首先尝试加载当前用户信息
    try {
      await userStore.getCurrentUser();
      console.log('App.vue: 用户信息加载成功');
    } catch (e) {
      console.warn('App.vue: 用户信息加载失败，可能未登录', e);
    }
    
    // 然后尝试加载权限数据
    try {
      await permissionStore.loadUserLocationPermissions();
      console.log('App.vue: 权限数据加载成功');
    } catch (e) {
      console.warn('App.vue: 权限数据加载失败', e);
    }
    
    // 初始化加载用户登录时间数据
    await initLoginTimesData();
  } catch (error) {
    console.error('App.vue: 初始化基础数据失败', error);
  }
})();

onMounted(async () => {
  try {
    // 应用启动时初始化所有数据
    isLoading.value = true;
    
    // Set initial language from localStorage
    const savedLanguage = localStorage.getItem('language');
    if (savedLanguage) {
      settingsStore.setLanguage(savedLanguage);
    }

    // 如果之前未成功初始化登录时间数据，再次尝试
    if (!loginTimesInitialized.value) {
      await initLoginTimesData();
    }
  } catch (error) {
    console.error('App.vue: onMounted初始化基础数据失败', error);
    ElMessage.error('加载部分基础数据失败，应用可能无法完全正常工作');
  } finally {
    isLoading.value = false;
  }
});

// 初始化用户登录时间数据的函数
const initLoginTimesData = async () => {
  try {
    if (loginTimesInitialized.value) {
      console.log('App.vue: 登录时间数据已初始化，跳过');
      return;
    }
    
    console.log('App.vue: 正在初始化用户登录时间数据');
    
    // 首先尝试获取当前位置ID
    let locationId = getLocationId();
    if (!locationId) {
      console.warn('App.vue: 未找到当前位置ID，尝试使用权限数据');
      
      // 确保权限数据已加载
      if (Object.keys(permissionStore.userLocationPermissions).length === 0) {
        try {
          await permissionStore.loadUserLocationPermissions();
        } catch (e) {
          console.warn('App.vue: 加载权限数据失败', e);
        }
      }
      
      // 再次尝试获取位置ID
      locationId = getLocationId();
    }
    
    if (!locationId) {
      console.warn('App.vue: 仍然无法获取位置ID，无法获取用户登录时间');
      return;
    }
    
    // 获取所有消息
    const response = await messagesApi.getMessages({
      locationId: locationId,
      getAllData: true
    });
    
    if (response && response.code === 200 && response.data) {
      let allMessages = [];
      // 处理可能的不同响应格式
      if (Array.isArray(response.data.list)) {
        allMessages = response.data.list;
      } else if (Array.isArray(response.data)) {
        allMessages = response.data;
      }
      
      console.log(`App.vue: 获取到 ${allMessages.length} 条消息`);
      
      // 处理用户登录时间
      const loginTimes = await messageHelper.getUserLoginTimes(allMessages);
      
      // 将登录时间存储到localStorage，以便在多个页面共享
      localStorage.setItem('userLoginTimes', JSON.stringify(loginTimes));
      
      // 存储登录消息到window对象，以便在不同组件中共享
      if (typeof window !== 'undefined') {
        // 过滤出登录消息
        const loginMessages = allMessages.filter(msg => {
          return msg.type === 'login' || msg.messageType === 'notification' || 
                (msg.content && msg.content.includes('登录'));
        });
        
        // 按创建时间降序排序
        loginMessages.sort((a, b) => {
          return new Date(b.createTime || b.create_time) - new Date(a.createTime || a.create_time);
        });
        
        window.latestLoginMessages = loginMessages;
        console.log('App.vue: 已将登录消息临时存储到window对象');
      }
      
      console.log('App.vue: 用户登录时间数据初始化完成');
      loginTimesInitialized.value = true;
    }
  } catch (error) {
    console.error('App.vue: 初始化用户登录时间数据失败', error);
  }
};

// 获取当前位置ID的函数
const getLocationId = () => {
  // 1. 首先尝试从localStorage获取当前选择的位置ID
  const currentLocationId = localStorage.getItem('currentLocationId');
  if (currentLocationId) {
    console.log('App.vue: 从localStorage获取到位置ID:', currentLocationId);
    return currentLocationId;
  }
  
  // 2. 其次尝试从permission store获取
  if (permissionStore.currentLocationId) {
    console.log('App.vue: 从permissionStore获取到位置ID:', permissionStore.currentLocationId);
    return permissionStore.currentLocationId;
  }
  
  // 3. 最后使用权限store中的第一个位置
  const userLocations = permissionStore.userLocationPermissions;
  if (userLocations && Object.keys(userLocations).length > 0) {
    const firstLocationId = Object.keys(userLocations)[0];
    console.log('App.vue: 使用权限中的第一个位置ID:', firstLocationId);
    return firstLocationId;
  }
  
  console.warn('App.vue: 未找到任何位置ID');
  return null;
};
</script>

<template>
  <div id="app">
    <el-config-provider :locale="elementLocale">
    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>
    </el-config-provider>
  </div>
</template>

<style>
/* 导入苹果设计系统字体 */
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');

:root {
  /* 苹果设计系统颜色变量 */
  --apple-background-light: #F5F5F7;
  --apple-background-dark: #1C1C1E;
  --apple-card-light: #FFFFFF;
  --apple-card-dark: rgba(44, 44, 46, 0.8);
  --apple-text-primary-light: #1D1D1F;
  --apple-text-primary-dark: #FFFFFF;
  --apple-text-secondary-light: #86868B;
  --apple-text-secondary-dark: #98989D;
  --apple-border-light: #E6E6E6;
  --apple-border-dark: #3A3A3C;
  --apple-button-light: rgba(118, 118, 128, 0.12);
  --apple-button-dark: rgba(118, 118, 128, 0.24);
  
  /* 品牌颜色 */
  --apple-blue: #007AFF;
  --apple-blue-dark: #0A84FF;
  --apple-green: #34C759;
  --apple-green-dark: #30D158;
  --apple-red: #FF3B30;
  --apple-red-dark: #FF453A;
  --apple-orange: #FF9500;
  --apple-orange-dark: #FF9F0A;
  --apple-purple: #AF52DE;
  --apple-purple-dark: #BF5AF2;
  --apple-brown: #A2845E;
  --apple-brown-dark: #B59F7D;
  
  /* 动画持续时间 */
  --animation-speed-fast: 0.2s;
  --animation-speed-medium: 0.3s;
  --animation-speed-slow: 0.5s;
  
  /* 交互变量 */
  --hover-scale: 1.02;
  --active-scale: 0.98;
  
  /* 其他样式变量 */
  --card-border-radius: 16px;
  --button-border-radius: 10px;
  --input-border-radius: 12px;
  
  /* 阴影效果 */
  --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.08);
  --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.1);
  --shadow-focus: 0 0 0 4px rgba(0, 122, 255, 0.2);
  
  /* 深色模式阴影 */
  --shadow-sm-dark: 0 2px 8px rgba(0, 0, 0, 0.2);
  --shadow-md-dark: 0 4px 16px rgba(0, 0, 0, 0.3);
  --shadow-lg-dark: 0 8px 24px rgba(0, 0, 0, 0.4);
  --shadow-focus-dark: 0 0 0 4px rgba(10, 132, 255, 0.3);
  
  /* 网格系统 */
  --grid-gap: 24px;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'San Francisco', sans-serif;
}

body {
  background-color: var(--apple-background-light);
  color: var(--apple-text-primary-light);
  transition: background-color var(--animation-speed-medium), color var(--animation-speed-medium);
}

@media (prefers-color-scheme: dark) {
  body {
    background-color: var(--apple-background-dark);
    color: var(--apple-text-primary-dark);
  }
}

/* 全局动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 卡片上浮动画 */
.float-up-enter-active {
  transition: transform var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1), 
              opacity var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1);
}

.float-up-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

/* 滑动动画 */
.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1), 
              opacity var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1);
}

.slide-right-enter-from,
.slide-left-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

.slide-right-leave-to,
.slide-left-enter-from {
  opacity: 0;
  transform: translateX(20px);
}

/* 毛玻璃效果 */
.glass-effect {
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  transition: backdrop-filter var(--animation-speed-medium);
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

@media (prefers-color-scheme: dark) {
  .glass-effect {
    background-color: rgba(44, 44, 46, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.08);
  }
}

/* 卡片悬浮效果 */
.hover-card {
  transition: transform var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1), 
              box-shadow var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1),
              background-color var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1);
  border-radius: var(--card-border-radius);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
}

.hover-card:hover {
  transform: translateY(-4px) scale(var(--hover-scale));
  box-shadow: var(--shadow-md);
  background-color: var(--apple-card-light);
}

.hover-card:active {
  transform: scale(var(--active-scale));
  box-shadow: var(--shadow-sm);
}

@media (prefers-color-scheme: dark) {
  .hover-card {
    box-shadow: var(--shadow-sm-dark);
  }
  
  .hover-card:hover {
    box-shadow: var(--shadow-md-dark);
    background-color: var(--apple-card-dark);
  }
  
  .hover-card:active {
    box-shadow: var(--shadow-sm-dark);
  }
}

/* 按钮浮动效果 */
.button-float {
  transition: transform var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1), 
              box-shadow var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1),
              background-color var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1);
  border-radius: var(--button-border-radius);
  overflow: hidden;
  position: relative;
}

.button-float::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.button-float:hover::before {
  left: 100%;
}

.button-float:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

.button-float:active {
  transform: translateY(0) scale(var(--active-scale));
  box-shadow: 0 2px 6px rgba(0, 122, 255, 0.2);
}

/* 脉冲效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(0, 122, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(0, 122, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(0, 122, 255, 0);
  }
}

.pulse {
  animation: pulse 2s infinite;
}

/* 自适应网格布局 */
.responsive-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: var(--grid-gap);
}

/* 统一元素样式 */
.apple-card {
  background-color: var(--apple-card-light);
  border-radius: var(--card-border-radius);
  box-shadow: var(--shadow-sm);
  overflow: hidden;
  transition: all var(--animation-speed-medium) cubic-bezier(0.33, 1, 0.68, 1);
}

.apple-button {
  background: linear-gradient(135deg, var(--apple-blue), #0062cc);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: var(--button-border-radius);
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1);
  position: relative;
  overflow: hidden;
}

.apple-button-text {
  background: transparent;
  color: var(--apple-blue);
}

.apple-button-primary {
  background: linear-gradient(135deg, #0A84FF, #0062cc);
}

.apple-button-danger {
  background: linear-gradient(135deg, var(--apple-red), #cc2b21);
}

.apple-input {
  background: #f8fafc;
  border: 2px solid transparent;
  border-radius: var(--input-border-radius);
  padding: 10px 15px;
  transition: all var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1);
  box-shadow: none;
}

.apple-input:hover {
  background: #fff;
  border-color: #e2e8f0;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

.apple-input:focus {
  background: #fff;
  border-color: var(--apple-blue);
  box-shadow: var(--shadow-focus);
  transform: translateY(-2px);
}

/* 统一加载动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 122, 255, 0.1);
  border-top-color: var(--apple-blue);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@media (prefers-color-scheme: dark) {
  .loading-spinner {
    border: 3px solid rgba(10, 132, 255, 0.1);
    border-top-color: var(--apple-blue-dark);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  :root {
    --grid-gap: 16px;
    --card-border-radius: 12px;
    --button-border-radius: 8px;
  }
  
  .responsive-grid {
    grid-template-columns: 1fr;
  }
}
</style>
